﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Threading;
using System.Data;
using System.Data.SqlClient;

namespace QLDiemDHBKServer
{
       
    public partial class QLDiemServer : Form
    {
        private Socket sock = null;
        protected SqlConnection con;
        protected SqlCommand cmd;
        protected SqlDataReader sda;
        protected String cn;

        public QLDiemServer()
        {
            InitializeComponent();
        }

        private void connect()
        {
            string cn = "Data Source=.;Initial Catalog=QLDiem;Integrated Security=True";

            try
            {
                con = new SqlConnection(cn);
                con.Open();
            }
            catch (Exception)
            {
                MessageBox.Show("Khong the ket noi co so du lieu", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnstartserver_Click(object sender, EventArgs e)
        {
            btnstartserver.Text = "In process...";
            Application.DoEvents();

            new Thread(new ThreadStart(processing)).Start();
        }
        private void processing()
        {
            IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 5656);
            sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            sock.Bind(ipEnd);
            sock.Listen(100);
            byte[] receive = new byte[1024];
            while (true)
            {
                Socket clientSock = sock.Accept();
                
                //DataSet dstest = new DataSet();
                //DataSet dstest = new QLDiemDataSet();
                clientSock.Receive(receive);
                string stringreceive = (string)DeserializeData(receive);
                if (stringreceive.Trim() == "khoa")
                {
                    string sql = "select * from Khoa";
                    DataTable table = (DataTable)query(sql);
                    clientSock.Send(SerializeData(table));
                }
                else  if (stringreceive.Trim() == "khoahoc")
                {
                    string sql = "select * from khoaHoc";
                    DataTable table = (DataTable)query(sql);
                    clientSock.Send(SerializeData(table));
                }
                else if (stringreceive.Trim() == "lop")
                {
                    string sql = "select * from Lop";
                    DataTable table = (DataTable)query(sql);
                    clientSock.Send(SerializeData(table));
                }
                else if (stringreceive.Trim() == "hocky")
                {
                    string sql = "select * from HocKy";
                    DataTable table = (DataTable)query(sql);
                    clientSock.Send(SerializeData(table));
                }
                else if (stringreceive.Trim().Substring(0,6) == "select")
                {
                    string sql = stringreceive.Trim();
                    DataTable table = (DataTable)query(sql);
                    clientSock.Send(SerializeData(table));
                }
                else if (stringreceive.Trim().Substring(0, 6) == "delete" || stringreceive.Trim().Substring(0, 6) == "update" || stringreceive.Trim().Substring(0, 6) == "insert")
                {
                    string sql = stringreceive.Trim();
                    changedata(sql);
                    clientSock.Send(SerializeData("Server: Cập nhật thành công"));
                }
            }
        }

        public object DeserializeData(byte[] theByteArray)
        {
            MemoryStream ms = new MemoryStream(theByteArray);
            BinaryFormatter bf1 = new BinaryFormatter();
            ms.Position = 0;
            return bf1.Deserialize(ms);
        }

        public byte[] SerializeData(Object o)
        {
            MemoryStream ms = new MemoryStream();
            BinaryFormatter bf1 = new BinaryFormatter();
            bf1.Serialize(ms, o);
            return ms.ToArray();
        }

        internal object query(string sql)
        {
            DataTable dt = new DataTable();
            connect();
            try
            {
                cmd = new SqlCommand(sql, con);
                cmd.CommandType = CommandType.Text;
                sda = cmd.ExecuteReader();
                dt.Load(sda);
            }
            catch (Exception)
            {
                return dt;
            }
            finally
            {
                con.Close();
            }
            return dt;
        }
        private void changedata(string sql)
        {
            try
            {
                connect();
                SqlCommand command = new SqlCommand();
                command.Connection = con;
                command.CommandText = sql;
                command.ExecuteNonQuery();
            }
            catch (Exception)
            {
                MessageBox.Show("Lỗi");
            }
        }
    }
}
